package com.chuangjiangx.member.stored.ddd.domain;

import com.chuangjiangx.member.stored.ddd.domain.stardard.MbrRefundContext;
import com.chuangjiangx.member.stored.ddd.domain.stardard.MbrRefundDomainResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.*;

/**
 * @author cj-ch
 * @date 2018/4/6 下午12:56
 */
public abstract class AbstractMbrRefund implements MbrRefund {
    protected final Logger logger = LoggerFactory.getLogger("pay");
    protected MbrRefundContext context;


    public AbstractMbrRefund(MbrRefundContext context) {
        this.context = context;
    }

    /**
     * 退款前
     */
    private Predicate<MbrRefundContext> beforeRefund;

    /**
     * 退款后
     */
    private BiConsumer<MbrRefundContext, MbrRefundDomainResult> afterRefund;


    /**
     * 由子类具体实现退款
     * @return
     */
    protected abstract MbrRefundDomainResult doRefund();



    @Override
    public MbrRefundDomainResult refund() {
        if (beforeRefund != null && !beforeRefund.test(this.context)) {
            //退款前置条件检查不通过时抛出异常
        }
        //执行退款业务代码
        MbrRefundDomainResult refundResult = doRefund();
        if (afterRefund != null) {
            //退款后业务逻辑处理
            afterRefund.accept(this.context,refundResult);
        }
        return refundResult;
    }



    public AbstractMbrRefund andBeforeRefund(Predicate<MbrRefundContext> predicate) {
        if (this.beforeRefund == null) {
            this.beforeRefund = predicate;
        } else {
            this.beforeRefund = this.beforeRefund.and(predicate);
        }
        return this;
    }

    public AbstractMbrRefund andAfterRefund(BiConsumer<MbrRefundContext, MbrRefundDomainResult> consumer) {
        if (this.afterRefund == null) {
            this.afterRefund = consumer;
        } else {
            this.afterRefund = this.afterRefund.andThen(consumer);
        }
        return this;
    }
}
